package _10_binary_tree.order.depth;

import _10_binary_tree.TreeNode;
import org.junit.Test;

import java.util.LinkedList;

/**
 * @author: mornd
 * @dateTime: 2023/6/11 - 15:19
 * 非递归实现深度优先遍历，搭配栈结构实现
 */
public class MyTest2 {

    /**
     * 构建树
     *          1
     *         /\
     *        2  3
     *       /\  /\
     *      4 7 5  6
     * @return
     */
    static TreeNode genericTestTree() {
        return new TreeNode(1, new
                TreeNode(2,
                new TreeNode(4), new TreeNode(7)),
                new TreeNode(3,
                        new TreeNode(5),
                        new TreeNode(6)));
    }

    /**
     * 31 = 红色
     * 32 = 绿色
     * 只看红色就是前序遍历
     * 只看绿色就是中序遍历
     * 后序需要另外处理，参照 MyTest2_2#postOrder
     */
    @Test
    public void test() {
        TreeNode root = genericTestTree();

        LinkedList<TreeNode> stack = new LinkedList<>();

        TreeNode curr = root;
        while (curr != null || !stack.isEmpty()) {
            if(curr != null) {
                stack.push(curr);
                printfColor(curr, 31);
                curr = curr.left;
            } else {
                TreeNode pop = stack.pop();
                printfColor(pop, 32);
                curr = pop.right;
            }
        }
    }

    /**
     * 控制台打印彩色字体
     * @param origin
     * @param color
     */
    void printfColor(Object origin, int color) {
//        System.out.printf("\033[%dm%s\033[0m%n", color, origin);
        System.out.printf("\033[%dm%s\033[0m\t", color, origin);
    }
}
